# -*- coding = utf-8 -*-
# @Time：2022/3/14 13:03
# @Author：3ic
# @File：control_switch.py
# @Software：PyCharm

import _thread
import time

from PyQt5.QtWidgets import QPushButton


class ControlSwitch(QPushButton):
    def __init__(self, parent_window=None, x=0, y=0, switch_interval=5):
        QPushButton.__init__(self, "start", parent_window)
        self.resize(120, 40)
        self.clicked.connect(self._onSwitch)
        self.setStyleSheet('color:#fff;font-size:32px;font-weight:700;background-color:#28B463;')
        self.move(x, y)

        self._is_started = False
        self._switch_interval = switch_interval
        self._last_switch_time = 0

        self._switchOnResponse = None
        self._switchOffResponse = None

    def _turnState(self, is_started_=None, wait_t=-1):
        if is_started_ is None:
            is_started_ = not self._is_started
        self._is_started = is_started_

        self.setText('brake' if is_started_ else 'start')
        self.setStyleSheet('color:#fff;font-size:32px;font-weight:700;background-color:#b3b3cc;')
        wait_t = self._switch_interval if wait_t <= 0 else wait_t
        time.sleep(wait_t - 0.1)
        if is_started_:
            self.setStyleSheet('color:#fff;font-size:32px;font-weight:700;background-color:#FF0099;')
        else:
            self.setStyleSheet('color:#fff;font-size:32px;font-weight:700;background-color:#28B463;')

    def _onSwitch(self):
        if time.time() - self._last_switch_time < self._switch_interval:
            return

        if self._is_started:
            if self._switchOffResponse is None or self._switchOffResponse() is False:
                return
        else:
            if self._switchOnResponse is None or self._switchOnResponse() is False:
                return
        _thread.start_new_thread(self._turnState, ())
        self._last_switch_time = time.time()

    def bindSwitchOnResponse(self, switchOnResponse_):
        self._switchOnResponse = switchOnResponse_

    def bindSwitchOffResponse(self, switchOffResponse_):
        self._switchOffResponse = switchOffResponse_

    def enforceToSwitchOff(self):
        if self._switchOffResponse is None or self._switchOffResponse() is False:
            return
        _thread.start_new_thread(self._turnState, (False,))
